﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTutorial.Core.Services;
using MVCTutorial.Core.Model;
using MVCTutorial.GUI.Web.ViewModels;

namespace MVCTutorial.GUI.Web.Controllers
{
	public class UserController
		: Controller
	{
		public ActionResult Index()
		{
			var users = ServiceProvider.UserService.GetAll();
			return View(users);
		}

		[HttpPost]
		public ActionResult Search(string nameLike)
		{
			var users = ServiceProvider.UserService.Search(nameLike);
			return PartialView("Partial/UserList", users);
		}

		public ActionResult Create()
		{
			ViewBag.Skills = ServiceProvider.SkillService.GetAll();
			return View();
		}

		[HttpPost]
		public ActionResult Create(string name, int?[] skills)
		{
			try
			{
				ServiceProvider.UserService.Create(name, skills);
				return RedirectToAction("Index");
			}
			catch
			{
				return View();
			}
		}

		public ActionResult Edit(int id)
		{
			var user = ServiceProvider.UserService.GetById(id);

			ViewBag.Skills = ServiceProvider.SkillService.GetAll();

			return View(new UserSkills(user));
		}

		[HttpPost]
		public ActionResult Edit(int id, string name, int?[] SkillIds)
		{
			try
			{
				ServiceProvider.UserService.Update(id, name, SkillIds);
				return RedirectToAction("Index");
			}
			catch (Exception e)
			{
				return View();
			}
		}

		public void Delete(int id)
		{
			ServiceProvider.UserService.Delete(id);
		}
	}
}
